package com.lijinjiang.util;

import com.lijinjiang.mode.PickerMode;

import javax.swing.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description 文本格式化程序
 * @Author lijinjiang
 * @Date 2024-12-30 10:52
 */

public class TextFieldFormatter extends JFormattedTextField.AbstractFormatter {

    private static final long serialVersionUID = 1L;
    private final PickerMode mode;

    public TextFieldFormatter(PickerMode mode) {
        this.mode = mode;
    }

    @Override
    public String valueToString(Object value) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(mode.getPattern());
        LocalDateTime time = (LocalDateTime) value;
        if (time != null) {
            return time.format(formatter);
        }
        return null;
    }

    @Override
    public Object stringToValue(String text) {
        if (text == null || text.equals("")) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(mode.getPattern());
        return LocalDateTime.parse(text, formatter);
    }

}
